﻿using System;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace WPFExcelReport
{
    public partial class TPCLTOOLS
    {
        #region ==PHOTOLINK===========
        public static readonly DependencyProperty PHOTOLINKProperty = DependencyProperty.Register("PHOTOLINK",
        typeof(string), typeof(TPCLTOOLS),
        new FrameworkPropertyMetadata("/ImagePackage;component/Images/Chart.png", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnPHOTOLINKChanged));
        public string PHOTOLINK
        {
            get
            {
                return (string)GetValue(PHOTOLINKProperty);
            }
            set
            {
                SetValue(PHOTOLINKProperty, value);
            }
        }
        private static void OnPHOTOLINKChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var src = sender as TPCLTOOLS;
            if (src != null)
            {
                src.PHOTOLINK = (string)e.NewValue;
            }
        }
        #endregion
        public void PreViewBMP(DataTable tb)
        {
            INFO = "";

            FormattedText str = null;
            DrawingVisual drawingVisual = new DrawingVisual();
            DrawingContext drawingContext = drawingVisual.RenderOpen();
            var query = from DataRow row in TBMain.AsEnumerable()
                        orderby Convert.ToDecimal(row.Field<string>("ROWNID")),
                       Convert.ToDecimal(row.Field<string>("PRCOND"))
                        select row;
            Rect rect = new Rect(0, 0, 0, 0);
            foreach (DataRow row in query)
            {
                //PRLX	PRLY	PRRX	PRRY	PRLTHICK	PRCTYPE	 	PRFONT	PRFONTSIZE	PRCONTENT
                string PRDES = row["PRDES"].ToString().Trim();
                if (PRDES == "N")
                    continue;
                string text = "";
                double PRLX = double.Parse(row["PRLX"].ToString().Trim());
                double PRLY = double.Parse(row["PRLY"].ToString().Trim());
                double PRRX = double.Parse(row["PRRX"].ToString().Trim());
                double PRRY = double.Parse(row["PRRY"].ToString().Trim());
                double PRCOND = double.Parse(row["PRCOND"].ToString().Trim());
                string PRLTHICK = row["PRLTHICK"].ToString().Trim();
                string PRCTYPE = row["PRCTYPE"].ToString().Trim();
                string PRFONT = Helpers.Helper.GetGB2312Value(row["PRFONT"].ToString().Trim());
                string PRFONTSIZE = row["PRFONTSIZE"].ToString().Trim();
                string PRCONTENT = Helpers.Helper.GetGB2312Value(row["PRCONTENT"].ToString());
                string PRCONTDES = Helpers.Helper.GetGB2312Value(row["PRCONTDES"].ToString());
                //PRLY = PRCOND * lineheight;
                //PRLX = PRLX * lineheight;
                double x = WPFDpi * PRLX / cPaper.PCLUnit;
                double y = WPFDpi * PRLY / cPaper.PCLUnit;
                switch (PRCTYPE)
                {
                    case "Paper":
                        break;
                    case "TXT":
                        double fsize = 12.0;
                        Typeface tp = new Typeface(this.FontFamily, FontStyles.Normal, FontWeights.Normal, new FontStretch());
                        var qf = from DataRow rf in TBMain.AsEnumerable()
                                 where rf["PRLY"].ToString() == PRFONT
                                 select rf;
                        foreach (DataRow rf in qf)
                        {
                            string ff = rf["PRCTYPDES"].ToString();
                            if (ff.Trim() == "") ff = "LetterGothic";
                            tp = GetFontFaimily(ff);
                            string[] finfo = rf["PRCONTENT"].ToString().Split(';');
                            if (finfo.Length < 5) continue;
                            //cFont.SymbolSet + ";" + cFont.Typeface + ";" + cFont.FontWeight + ";" + cFont.FontStyle + ";" + cFont.FontPitch + ";" + cFont.FontSpacing;
                            //300/1.5/10 cPaper.PCLUnit * 2.54 / cFont.FontPitch
                            if (finfo[4] == "") continue;
                            if (finfo[4] == "0")
                            {
                                fsize = 12.0;
                            }
                            else
                            {
                                //System.Convert.ToInt32(cPaper.FONTCpi * 2.54 / cFont.FontPitch * value.Length)
                                //end position=
                                /*
                                double end = double.Parse(PRFONTSIZE);
                                double start = PRLX;
                                fsize = (((end - start) / 300) * WPFDpi) / PRCONTENT.Count();*/
                                fsize = 0.6*Convert.ToInt16(WPFDpi * 2.54 / double.Parse(finfo[4]));

                            }
                            //PCL Def charactors per inch
                            //windows each fonts how many pixels;
                            switch (finfo[3])
                            {
                                case "0":
                                    break;
                            }
                            switch (finfo[2])
                            {
                                case "0":
                                    tp = new Typeface(tp.FontFamily, FontStyles.Normal, FontWeights.Normal, new FontStretch());
                                    break;
                                case "1":
                                    tp = new Typeface(tp.FontFamily, FontStyles.Normal, FontWeights.Medium, new FontStretch());
                                    break;
                                case "2":
                                    tp = new Typeface(tp.FontFamily, FontStyles.Normal, FontWeights.Bold, new FontStretch());
                                    break;
                            }
                        }

                        str = new FormattedText(PRCONTENT.Replace("_T", "\\"),
                            new CultureInfo("en-us"),
                            FlowDirection.LeftToRight,
                            tp,
                            fsize,
                           System.Windows.Media.Brushes.Black);
                        drawingContext.DrawText(str, new System.Windows.Point(Convert.ToDouble(x), Convert.ToDouble(y)));
                        INFO += x + "," + y + ":" + PRCONTENT + ";";
                        break;
                    case "RECT":
                        Rect rectangle = new Rect();
                        string[] rects = PRCONTENT.Split(';');
                        if (rects.Length < 5) continue;
                        rectangle.X = WPFDpi * double.Parse(rects[0]) / cPaper.PCLUnit;
                        rectangle.Y = WPFDpi * double.Parse(rects[1]) / cPaper.PCLUnit;
                        rectangle.Width = WPFDpi * double.Parse(rects[2]) / cPaper.PCLUnit;
                        rectangle.Height = WPFDpi * double.Parse(rects[3]) / cPaper.PCLUnit;
                        System.Windows.Media.Pen pen = new System.Windows.Media.Pen(System.Windows.Media.Brushes.Black, WPFDpi * double.Parse(rects[4]) / cPaper.PCLUnit);
                        drawingContext.DrawRectangle(System.Windows.Media.Brushes.Black, pen, rectangle);
                        break;
                }
            }
            // Text to render on the image.
            // The Visual to use as the source of the RenderTargetBitmap. 
            drawingContext.Close();
            if (!System.IO.Directory.Exists(@"D:\ITXRPRT\Documents\Print"))
            {
                System.IO.Directory.CreateDirectory(@"D:\ITXRPRT\Documents\Print");
            }
            RenderTargetBitmap rtb = new RenderTargetBitmap(System.Convert.ToInt32(PNGDpi * cPaper.Width300DPI / cPaper.PCLUnit),
                  System.Convert.ToInt32(PNGDpi * cPaper.Height300DPI / cPaper.PCLUnit), PNGDpi, PNGDpi, PixelFormats.Pbgra32);
            rtb.Render(drawingVisual);
            string file = @"D:\ITXRPRT\Documents\Print\PWB" + Guid.NewGuid().ToString() + ".";
            GenerateImage(rtb, ImageFormat.TIF, ref file);
            PHOTOLINK = file;
            //RefreshImage(file, cPaper);
        }

        public enum ImageFormat { JPG, BMP, PNG, GIF, TIF }

        void GenerateImage(BitmapSource bitmap, ImageFormat format, ref string file)
        {
            file += format.ToString();
            using ( Stream stm = File.Create(file))
            { 
                BitmapEncoder encoder = null;

                switch (format)
                {
                    case ImageFormat.JPG:
                        encoder = new JpegBitmapEncoder();
                        break;
                    case ImageFormat.PNG:
                        encoder = new PngBitmapEncoder();
                        break;
                    case ImageFormat.BMP:
                        encoder = new BmpBitmapEncoder();
                        break;
                    case ImageFormat.GIF:
                        encoder = new GifBitmapEncoder();
                        break;
                    case ImageFormat.TIF:
                        encoder = new TiffBitmapEncoder();
                        break;
                    default:
                        throw new InvalidOperationException();
                }

                encoder.Frames.Add(BitmapFrame.Create(bitmap));
                encoder.Save(stm);
            }
        }

        private void RefreshImage(string file, PaperInfo paper)
        {
            // Create source
            BitmapImage bmp = new BitmapImage();

            // BitmapImage.UriSource must be in a BeginInit/EndInit block
            bmp.BeginInit();
            bmp.CacheOption = BitmapCacheOption.OnLoad;

            bmp.UriSource = new Uri(file);
            bmp.DecodePixelWidth = System.Convert.ToInt32(WPFDpi * paper.Width300DPI / 300);
            bmp.DecodePixelHeight = System.Convert.ToInt32(WPFDpi * paper.Height300DPI / 300);
            bmp.EndInit();
            //set image source
            this.imgpriew.Source = bmp;

        }
    }

}
